from rest_framework.mixins import UpdateModelMixin, ListModelMixin
from api.models import WmsInventory
from django.db import transaction
from rest_framework.response import Response

class UpdateAllModelMixin(UpdateModelMixin, ListModelMixin):
    def update(self, request, *args, **kwargs):
        id = request.data.get('product_id')
        quantity = int(request.data.get('quantity'))# 剩余需要扣减的量
        
        # 1. 筛选匹配 product_id 的记录，并按 quantity 降序排序
        matched_instances = WmsInventory.objects.filter(product_id=id).order_by('-quantity')
        
        if not matched_instances.exists():
            return(f"No inventory found for product_id: {id}")

        # 2. 遍历扣减库存
        updated_instances = []

        for instance in matched_instances:
            if quantity <= 0:
                break  # 已完全扣减，退出循环

            if instance.quantity >= quantity:
                # 当前记录足够扣减
                instance.quantity -= quantity
                quantity = 0
            else:
                # 当前记录不足，全部扣减
                quantity -= instance.quantity
                instance.quantity = 0

            updated_instances.append(instance)

        # 3. 检查是否完全扣减
        if quantity > 0:
            return(
                f"Insufficient inventory. {quantity} units remaining to deduct."
            )

        # 4. 批量更新数据库（事务保障原子性）
        with transaction.atomic():
            WmsInventory.objects.bulk_update(
                updated_instances,
                fields=['quantity']  # 只更新 quantity 字段
            )

        return Response(status=200)